/**
 * @class   ModemDslImpl
 * @brief   Implementation of Modem class, customized for a generic xDSL 
 *          modem/router on a NIX system, controlled through a bash script.
 *
 *          Real device is virtually controlled through a bash script. Its exit
 *          code will be parsed to update status and config operations.
 *          Connection status (and stats) may be updated automatically by an
 *          internal thread (frequency is configurable).
 *
 *          Default (bash) script supports some basic commands (actions):
 *           - connect
 *           - disconnect
 *           - reconnect
 *           - check [optional: ip/hostname, 'google.com' by default]
 *
 *          You may need to customize the script for you system/settings.
 *          Standard script is configured for PPPoE driver (PPP over Ethernet),
 *          some PPPoE command-line tools are evaluated by the script which
 *          returns a standardized ExitCode (parsed by the class).
 *
 *          Moreover this implementatio retrieve stats using system access calls.
 *
 * @note    BASED on pppstatus 0.4.2 by Gabriel Montenegro
 *
 *
 * @note    This device is platform-dependent, UNIX/Linux only.
 * @note    This device is partially based on a bash script.
 *
 *
 * \par script specification
 *  ExitCode 0 : Operation Succeded.
 *
 *  ExitCode 1 : Operation Failed.
 *  ExitCode 10 : Operation Unknown (command not found).
 *
 * @warning The script may require a 'root' permission (login) to execute some commands.
 *
 * @see     _ModemDsl_DEFAULT_Script (bin/scripts/dslmodem.sh)
 ****************************************************************************
 * @version 0.8.467 $Id: ModemDslImpl.h 2866 2010-08-07 15:01:48Z alex $
 * @author  Alessandro Polo
 * @date    Released on 2009-06-04
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

#ifndef __WOSH_DEVICES_ModemDsl_H__
 #define __WOSH_DEVICES_ModemDsl_H__

 #include <woshDefs.h>
 #include <core/Mutex.h>
 #include <core/BundleGenericWorker.h>

 #include <interfaces/devices/Modem.h>

 #include "IModemDslListener.h"

using namespace wosh;

class ModemDslImpl : public BundleGenericWorker
 {
	public:
		/**
		 * @brief   Default constructor. Init vars.
		 * @param bundle [in] the parent bundle, see BundleGenericWorker interface
		 */
		ModemDslImpl( BundleGeneric& bundle );
		/**
		 * @brief   Deconstructor. If thread is stll running, it will be stopped.
		 */
		virtual ~ModemDslImpl();

/** @name Setters
 * @{
 ******************************************************************************/
	public:
		/**
		 * @brief   Set period of refresh loop.
		 * @param value [in] refresh period in seconds
		 * @note    method is reentrant (thread safe)
		 */
		void setRefreshFrequency( unsigned long value );
		/**
		 * @brief   Set full path of support script, used to control the modem
		 * @param value [in] full path of script (example: bin/scripts/dslmodem.sh)
		 * @note    method is reentrant (thread safe)
		 */
		void setControlScript( const std::string& value );
		/**
		 * @brief   Set address used while checking connection through ping
		 * @param value [in] IPv4 or hostname address (example: www.google.com)
		 * @note    method is reentrant (thread safe)
		 */
		void setPingCheckAddress( const std::string& value );
		/**
		 * @brief   Set POSIX interface associated with connection
		 * @param value [in] interface name (example: ppp0)
		 * @note    method is reentrant (thread safe)
		 */
		void setPppInterface( const std::string& value );
		/**
		 * @brief   Set the IModemDslListener interface for callbacks.
		 * @param listener [in] pointer to object which implements callback-functions
		 * @note    Call this method only once, after creation, it's not reetrant!
		 */
		void setModemListener( IModemDslListener* listener );

//@}
/** @name Getters
 * @{
 ******************************************************************************/
	public:
		/**
		 * @brief   Get period of refresh loop.
		 * @return  refresh period in seconds
		 */
		long getRefreshFrequency() const;
		/**
		 * @brief   Get full path of support script, used to control the modem
		 * @return  full path of script (example: bin/scripts/dslmodem.sh)
		 */
		std::string getControlScript() const;
		/**
		 * @brief   Get address used while checking connection through ping
		 * @return  IPv4 or hostname address (example: www.google.com)
		 */
		std::string getPingCheckAddress() const;
		/**
		 * @brief   Get POSIX interface associated with connection
		 * @return  interface name (example: ppp0)
		 */
		std::string getPppInterface() const;
		/**
		 * @brief   Get IModemDslListener interface class for callbacks.
		 * @return  pointer to object which implements callback-functions
		 */
		IModemDslListener* getModemListener();

//@}
/** @name Modem Interface
 * @{
 ******************************************************************************/
	public:
		/**
		 * @brief   Connect modem. Raise Fact when connected.
		 * @param params [in] Connection parameters (when required)
		 * @return  WRET_ERR_INTERNAL if something went wrong; WRET_OK is modem has been disconnected.
		 * @see     controlScript
		 */
		virtual WRESULT connect( std::string params = "" );
		/**
		 * @brief   Disconnect modem. Raise Fact when disconnected.
		 * @return  WRET_ERR_INTERNAL if something went wrong; WRET_OK is modem has been disconnected.
		 * @see     controlScript
		 */
		virtual WRESULT disconnect();
		/**
		 * @brief   Reconnect modem. Raise Fact when connected.
		 * @return  WRET_ERR_INTERNAL if something went wrong; WRET_OK is modem has been disconnected.
		 * @see     controlScript
		 */
		virtual WRESULT reconnect();
		/**
		 * @brief   Force connection check: using control-script with 'check <PING-ADDRESS>' command.
		 *          Raise Fact when connection state changed.
		 * @return  WRET_ERR_INTERNAL if something went wrong; WRET_OK if check was successful.
		 * @see     controlScript
		 * @see     pingCheckAddress
		 */
		virtual WRESULT checkConnected();

		/**
		 * @brief   Force stats reset.
		 * @return  WRET_NOT_IMPLEMENTED or WRET_ERR_ILLEGAL_USE if feature is not available;
		 *          WRET_ERR_INTERNAL if something went wrong; WRET_OK if check was successful.
		 */
		virtual WRESULT resetStats()							{ return getStats(false, 0); }

//@}
/** @name Internal methods
 * @{
 ******************************************************************************/
	protected:
		/**
		 * @brief   Perform periodic checkConnected() to update stats.
		 * @see     running
		 * @see     autoRefreshFrequency
		 */
		virtual void runThread();
		/**
		 * @brief   Retrieve stats of the modem
		 * @param raiseevent [in] when true it will raise (callback) event
		 * @param sec_span [in] set to '0' to reset dynamic stats (such as speed), a lower value
		 *          to ignore dynamic tags, a positive value to update values according to given time offset in seconds
		 * @return  WRET_ERR_INTERNAL if something went wrong; WRET_OK if stats has been updated
		 * @note    synch implementation
		 * @see     stats
		 * @see     modem_StatsUpdate()
		 */
		WRESULT getStats( bool raiseevent, int sec_span );
		/**
		 * @brief   Execute control-script using C system call
		 * @param params [in] parameters to be passes to the script
		 * @note    synch implementation
		 * @see     controlScript
		 * @see     system
		 */
		int callControlScript( const std::string& params );
		/**
		 * @brief   Raise a connection-state (callback) event
		 * @param state [in] current connection state
		 * @note    synch implementation
		 * @see     modem_ConnectionState()
		 */
		void raiseEvent( wosh::interfaces::devices::Modem::CONNECTION_STATE state );

//@}
	protected:
		std::string controlScript;			///< bash script to connect/disconnect/force-check
		long autoRefreshFrequency;			///< frequency check in seconds
		std::string pingCheckAddress;		///< address to ping (used by checkConnected, script)
		std::string pppInterface;			///< ppp interface (by defautl 'ppp0')
		IModemDslListener* modemListener;	///< callbacks for stats (such as ModemDslBundle*)
		MutexRW configMux;					///< Mutex of configuration (previous vars)
		pppStats stats;						///< last available stats 


}; // class def

#endif //__WOSH_DEVICES_ModemDsl_H__
